package com.windward.vii.web.controller;

import com.windward.vii.common.Constants;
import com.windward.vii.common.JsonResult;
import com.windward.vii.config.PushConfig;
import com.windward.vii.dao.entity.AssetUserAccount;
import com.windward.vii.dao.mapper.AssetUserAccountMapper;
import com.windward.vii.service.AssetUserAccountService;
import com.windward.vii.service.apns.PushService;
import com.windward.vii.service.rongcloud.RongCloudProxy;
import com.windward.vii.utils.StringUtils;
import com.windward.vii.utils.ThreadPoolManager;
import com.windward.vii.service.rongcloud.messages.extend.CallMessage;
import com.windward.vii.service.rongcloud.models.CodeSuccessResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by tiansj on 2017/10/14.
 */
@Controller
@RequestMapping(value = "/")
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);
    @Resource
    PushConfig pushConfig;
    @Resource
    AssetUserAccountService assetUserAccountService;

//    @RequestMapping(value = "v1/api0/user/test", method = RequestMethod.GET)
//    @ResponseBody
//    public JsonResult test(@RequestParam String thirdOption, HttpServletRequest request) {
//
//        logger.info("thirdOption={}", thirdOption);
//
//        User user = new User();
//        user.setId(5L);
//        user.setThirdOption(thirdOption);
//
//        boolean b = userService.updateByPrimaryKeySelective(user);
//        logger.info("updateByPrimaryKeySelective is success={}", b);
//
//        return new JsonResult(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG);
//    }

    @Resource
    RongCloudProxy rongCloudProxy;

    @RequestMapping(value = "v1/api0/test/push", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult testPush(@RequestHeader(value="User-Agent") String userAgent) {
        logger.info("User-Agent:{}", userAgent);
        logger.info("************************Push********************");
//        JPushClient jPushClient = new JPushClient(pushConfig.getAppSecret(), pushConfig.getAppKey());
//
//        CallMessage callMessage = new CallMessage("1", "3947857",
//                "http://vii-img.oss-cn-beijing.aliyuncs.com/user_3947846_avatar_20170930014151347-6291.png",
//                "鲸鱼");

//        HashMap<String, String> extras = new HashMap();
//        extras.put("msg_type", CallMessage.TYPE);
//        extras.put("msg_content", callMessage.toString());
//
//        IosNotification iosNotification = IosNotification.newBuilder()
//                .setAlert("鲸鱼 邀请你进行视频通话")
//                .setSound("ring.mp3")
//                .setContentAvailable(true)
//                .setMutableContent(true)
//                .addExtras(extras)
//                .build();
//        Notification notification = Notification.newBuilder().addPlatformNotification(iosNotification).build();
//        PushPayload pushPayload = PushPayload.newBuilder()
//                .setPlatform(Platform.android_ios())
//                .setAudience(Audience.alias("3947860"))
//                .setNotification(notification)
//                .build();
//        try {
//            PushResult pushResult = jPushClient.sendPush(pushPayload);
//            logger.info("connect: notification={}", JSON.toJSONString(notification));
//            logger.info("connect: PushPayload={}", JSON.toJSONString(pushPayload));
//            logger.info("connect: PushResult={}", pushResult.toString());
//            JsonResult jsonResult = JsonResult.success();
//            jsonResult.setBody(pushResult);
//            return  jsonResult;
//        } catch (APIConnectionException e) {
//            e.printStackTrace();
//        } catch (APIRequestException e) {
//            e.printStackTrace();
//        }


        CallMessage callMessage = new CallMessage("1", "5",
                "http://vii-img.oss-cn-beijing.aliyuncs.com/user_3947846_avatar_20170930014151347-6291.png",
                "鲸鱼", 0);

        try {
            PushService.sendPush(callMessage, "鲸鱼 邀请你进行视频通话", "255b910e87bdd2c67a695f1f8bd1f90f62d7aff07d8cb31eb2be5af49ec8c55d");
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonResult.error();

    }

    @RequestMapping(value = "v1/api0/test/push1", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult testPush1(@RequestHeader(value="User-Agent") String userAgent) {
        logger.info("User-Agent:{}", userAgent);
        logger.info("************************Push********************");
//        JPushClient jPushClient = new JPushClient(pushConfig.getAppSecret(), pushConfig.getAppKey());
//
//        CallMessage callMessage = new CallMessage("1", "3947857",
//                "http://vii-img.oss-cn-beijing.aliyuncs.com/user_3947846_avatar_20170930014151347-6291.png",
//                "鲸鱼");

//        HashMap<String, String> extras = new HashMap();
//        extras.put("msg_type", CallMessage.TYPE);
//        extras.put("msg_content", callMessage.toString());
//
//        IosNotification iosNotification = IosNotification.newBuilder()
//                .setAlert("鲸鱼 邀请你进行视频通话")
//                .setSound("ring.mp3")
//                .setContentAvailable(true)
//                .setMutableContent(true)
//                .addExtras(extras)
//                .build();
//        Notification notification = Notification.newBuilder().addPlatformNotification(iosNotification).build();
//        PushPayload pushPayload = PushPayload.newBuilder()
//                .setPlatform(Platform.android_ios())
//                .setAudience(Audience.alias("3947860"))
//                .setNotification(notification)
//                .build();
//        try {
//            PushResult pushResult = jPushClient.sendPush(pushPayload);
//            logger.info("connect: notification={}", JSON.toJSONString(notification));
//            logger.info("connect: PushPayload={}", JSON.toJSONString(pushPayload));
//            logger.info("connect: PushResult={}", pushResult.toString());
//            JsonResult jsonResult = JsonResult.success();
//            jsonResult.setBody(pushResult);
//            return  jsonResult;
//        } catch (APIConnectionException e) {
//            e.printStackTrace();
//        } catch (APIRequestException e) {
//            e.printStackTrace();
//        }


        CallMessage callMessage = new CallMessage("1", "5",
                "http://vii-img.oss-cn-beijing.aliyuncs.com/user_3947846_avatar_20170930014151347-6291.png",
                "鲸鱼", 0);

        try {
            PushService.sendPush(callMessage, "鲸鱼 邀请你进行视频通话", "ce7beecdf6cda6772956e8a96e658ab0743ada8d7f361b29332865ee362ff9e4");
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonResult.error();

    }

    @Resource
    AssetUserAccountMapper assetUserAccountMapper;

    @RequestMapping(value = "v1/api0/test/im/refresh", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult imRefresh() {
        List<AssetUserAccount> all = assetUserAccountMapper.getAllUser();
        if(all == null || all.size() == 0) {
            return JsonResult.success("没有用户可以更新");
        }
        logger.info("imRefresh: total={}", all.size());
        int i = 1;
        for(AssetUserAccount account : all) {
            asyncUpdateImNickname(account, i);
            i++;
        }
        return JsonResult.success();
    }

    private void asyncUpdateImNickname(AssetUserAccount userAccount, int index) {
        ThreadPoolManager.getInstance().addExecuteTask(new Runnable() {
            @Override
            public void run() {
                try {
                    String avatar = userAccount.getAvatar();
                    if(StringUtils.isBlank(avatar)) {
                        avatar = Constants.User.DEFAULT_AVATAR_URL;
                    }
                    logger.info("imRefresh: index={} ======================================", index);
                    logger.info("imRefresh: uid={}, nickname={}, avatar={}", userAccount.getUid(), userAccount.getNickname(), avatar);
                    CodeSuccessResult messagePublishSystemResult = rongCloudProxy.getInstance().user.refresh(
                            String.valueOf(userAccount.getUid()),
                            userAccount.getNickname(),
                            avatar);
                    logger.info("imRefresh: result={}", messagePublishSystemResult.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @RequestMapping(value = "v1/api0/test/register/im", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult testPushRegisterImTips() {
        assetUserAccountService.asyncSendRegisterImTips(5L);
        return JsonResult.success();
    }
}
